var geocoder;
var map;
var marker;

function initialize() {

  var santiago = new google.maps.LatLng(-33.4691199, -70.641997);

  //se ingresan las opciones del mapa
  map = new google.maps.Map(document.getElementById('map_canvas'), {
    center: santiago,
    zoom: 11,

    panControl: true,
    zoomControl: true,
    mapTypeControl: false,
    scaleControl: true,
    streetViewControl: false,
    overviewMapControl: true,
    rotateControl :false,

    panControlOptions: {
      position: google.maps.ControlPosition.TOP_RIGHT
    },
    zoomControlOptions: {
      style: google.maps.ZoomControlStyle.LARGE,
      position: google.maps.ControlPosition.TOP_RIGHT
    },
    mapTypeId: google.maps.MapTypeId.ROADMAP
  });


  //se crea el geocoder
  geocoder = new google.maps.Geocoder();
  //se crea el marcador
  marker = new google.maps.Marker({
    map: map,
    draggable: true,
    title:"Me robaron aquí"
  });


  $(function() {
  //uso de autocomplete, de la libreria jqueryui
  $("#input_buscar").autocomplete({
    //This bit uses the geocoder to fetch address values

    source: function(request, response) {


      geocoder.geocode( {'address': request.term }, function(results, status) {
        response($.map(results, function(item) {
          return {
            label:  item.formatted_address,
            value: item.formatted_address,
            latitude: item.geometry.location.lat(),
            longitude: item.geometry.location.lng()
          }
        }));
      })


    },



    //This bit is executed upon selection of an address
    select: function(event, ui) {
      $("#latitude").html(ui.item.latitude);
      $("#longitude").html(ui.item.longitude);
      //se obtiene una locacion
      var location = new google.maps.LatLng(ui.item.latitude, ui.item.longitude);
      //se le da esa locacion al marcador
      marker.setPosition(location);
      //se centra el mapa en esa locacion
      map.setCenter(location);
    }

  });
});

google.maps.event.addListener(marker, 'drag', function() {
  geocoder.geocode({'latLng': marker.getPosition()}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      if (results[0]) {
        $('#input_buscar').val(results[0].formatted_address);
        $('#latitude').html(marker.getPosition().lat());
        $('#longitude').html(marker.getPosition().lng());
      }
    }
  });
});

google.maps.event.addListener(map, 'click', function(event) {
  marker.setPosition(event.latLng);

  geocoder.geocode({'latLng': marker.getPosition()}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      if (results[0]) {
        $('#input_buscar').val(results[0].formatted_address);
        $('#latitude').html(marker.getPosition().lat());
        $('#longitude').html(marker.getPosition().lng());
      }
    }
  });

});
}